package com.atguigu.microshop.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.microshop.product.dao.CategoryDao;
import com.atguigu.microshop.product.entity.CategoryEntity;
import com.atguigu.microshop.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //获取所有分类数据
        List<CategoryEntity> data= baseMapper.selectList(null);
        //找到一级分类
        List<CategoryEntity> Level1Tree=data.stream().filter((categoryEntity)->
              categoryEntity.getParentCid()==0
        ).map((menu)->{
            menu.setChildren(getChildren(menu,data));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        //组装成tree返回
        return Level1Tree;
    }
    /**
     * 递归获取子菜单,root代表子菜单，all全部菜单，stream().filter为数组过滤方法，map为映射方法
     * **/
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> Children=all.stream().filter((categoryEntity)->{
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity->{//映射实体类的自定义
            categoryEntity.setChildren(getChildren(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{//排序，menu1是当前菜单，menu2代表后一个菜单
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return Children;
    };


    /*
     * 排序,根据order排序
     */
    public Comparator<CategoryEntity> Sort(){
        Comparator<CategoryEntity> comparator = new Comparator<CategoryEntity>() {
            @Override
            public int compare(CategoryEntity o1, CategoryEntity o2) {
                if (o1.getSort() != o2.getSort()){
                    return (o1.getSort()==null?0:o1.getSort()) - (o2.getSort()==null?0:o2.getSort());
                }
                return 0 ;
            }
        };
        return comparator;
    }

    @Override
    public List<CategoryEntity> getMenuTree(){
        Map<String,Object> data = new HashMap<String,Object>();
        try {
            //获取所有分类数据
            List<CategoryEntity> allCate= baseMapper.selectList(null);
            //根节点
            List<CategoryEntity> rootMenu = new ArrayList<CategoryEntity>();
            for (CategoryEntity nav : allCate) {
                if (nav.getParentCid()==0){ //父节点是0的，为根节点。
                    rootMenu.add(nav);
                }
            }
            /* 根据Category类的Sort排序 */
            Collections.sort(rootMenu, Sort());
            //为根菜单设置子菜单，getClild是递归调用的
            for (CategoryEntity nav : rootMenu) {
                /* 获取根节点下的所有子节点 使用getChild方法*/
                List<CategoryEntity> childList = getChild(nav.getCatId(), allCate);
                nav.setChildren(childList);//给根节点设置子节点
            }
            return rootMenu;
        }catch (Exception e) {
            data.put( "success" , "false" );
            data.put( "list" , new ArrayList());
            return (List<CategoryEntity>) data;
        }
    }

    @Override
    public void removeCateByIds(List<Long> asList) {
        //TODO 删除前看看菜单是否被其他地方应用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }


    /**
     * 获取子节点
     * @param id 父节点id
     * @param allMenu 所有菜单列表
     * @return 每个根节点下，所有子菜单列表
     */
    public List<CategoryEntity> getChild(Long id,List<CategoryEntity> allMenu){
        //子菜单
        List<CategoryEntity> childList = new ArrayList<CategoryEntity>();
        for (CategoryEntity nav : allMenu) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (nav.getParentCid()==id){
                childList.add(nav);
            }
        }
        //递归
        for (CategoryEntity nav : childList) {
            nav.setChildren(getChild(nav.getCatId(), allMenu));
        }
        Collections.sort(childList,Sort()); //排序
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0 ){
            return new ArrayList<CategoryEntity>();
        }
        return childList;
    }


}